{% extends "base.html" %}

{% block title %}回收站 - XbyJob{% endblock %}

{% block content %}
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">回收站</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <div class="btn-group me-2">
            <button type="button" class="btn btn-outline-secondary" onclick="refreshRecycleItems()">
                <i class="fas fa-sync-alt me-1"></i>刷新
            </button>
            <button type="button" class="btn btn-warning" onclick="cleanExpiredItems()">
                <i class="fas fa-broom me-1"></i>清理过期项目
            </button>
        </div>
    </div>
</div>

<!-- 统计信息 -->
<div class="row mb-3">
    <div class="col-md-3">
        <div class="card text-center">
            <div class="card-body">
                <h5 class="card-title text-primary" id="totalItems">0</h5>
                <p class="card-text">总项目数</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card text-center">
            <div class="card-body">
                <h5 class="card-title text-info" id="scriptItems">0</h5>
                <p class="card-text">脚本文件</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card text-center">
            <div class="card-body">
                <h5 class="card-title text-warning" id="folderItems">0</h5>
                <p class="card-text">文件夹</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card text-center">
            <div class="card-body">
                <h5 class="card-title text-danger" id="expiredItems">0</h5>
                <p class="card-text">过期项目</p>
            </div>
        </div>
    </div>
</div>

<!-- 批量操作工具栏 -->
<div class="row mb-3" id="batchToolbar" style="display: none;">
    <div class="col-12">
        <div class="card border-primary">
            <div class="card-body py-2">
                <div class="d-flex justify-content-between align-items-center">
                    <div class="d-flex align-items-center">
                        <span class="me-3">已选择 <span id="selectedCount">0</span> 项</span>
                        <div class="btn-group btn-group-sm">
                            <button type="button" class="btn btn-outline-primary" onclick="selectAll()">
                                <i class="fas fa-check-square me-1"></i>全选
                            </button>
                            <button type="button" class="btn btn-outline-secondary" onclick="clearSelection()">
                                <i class="fas fa-square me-1"></i>取消选择
                            </button>
                        </div>
                    </div>
                    <div class="btn-group btn-group-sm">
                        <button type="button" class="btn btn-success" onclick="batchRestore()">
                            <i class="fas fa-undo me-1"></i>批量恢复
                        </button>
                        <button type="button" class="btn btn-danger" onclick="batchPermanentDelete()">
                            <i class="fas fa-trash-alt me-1"></i>批量永久删除
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 回收站项目列表 -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h6 class="card-title mb-0">回收站项目</h6>
                <div class="d-flex align-items-center">
                    <div class="form-check me-3">
                        <input class="form-check-input" type="checkbox" id="batchModeToggle">
                        <label class="form-check-label" for="batchModeToggle">
                            批量操作模式
                        </label>
                    </div>
                    <div class="btn-group btn-group-sm">
                        <button type="button" class="btn btn-outline-secondary" onclick="filterByType('all')" id="filterAll">
                            全部
                        </button>
                        <button type="button" class="btn btn-outline-info" onclick="filterByType('script')" id="filterScript">
                            脚本
                        </button>
                        <button type="button" class="btn btn-outline-warning" onclick="filterByType('folder')" id="filterFolder">
                            文件夹
                        </button>
                        <button type="button" class="btn btn-outline-danger" onclick="filterByType('expired')" id="filterExpired">
                            过期
                        </button>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div id="recycleContainer">
                    <div class="text-center">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 恢复确认模态框 -->
<div class="modal fade" id="restoreModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">确认恢复</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>确定要恢复选中的项目吗？</p>
                <div id="restoreItemsList"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-success" onclick="confirmRestore()">确认恢复</button>
            </div>
        </div>
    </div>
</div>

<!-- 永久删除确认模态框 -->
<div class="modal fade" id="permanentDeleteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title text-danger">确认永久删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>警告：</strong>此操作将永久删除选中的项目，无法恢复！
                </div>
                <p>确定要永久删除以下项目吗？</p>
                <div id="deleteItemsList"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="confirmPermanentDelete()">确认删除</button>
            </div>
        </div>
    </div>
</div>

<script>
let currentFilter = 'all';
let recycleItems = [];
let selectedItems = [];
let batchMode = false;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    loadRecycleItems();
    
    // 批量操作模式切换
    document.getElementById('batchModeToggle').addEventListener('change', function() {
        batchMode = this.checked;
        toggleBatchMode();
    });
});

// 加载回收站项目
function loadRecycleItems() {
    fetch('/api/recycle')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                recycleItems = data.data.items;
                updateStatistics(recycleItems);
                renderRecycleItems();
            } else {
                showToast('加载回收站项目失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('加载回收站项目失败', 'error');
        });
}

// 更新统计信息
function updateStatistics(items) {
    const total = items.length;
    const scripts = items.filter(item => item.type === 'script').length;
    const folders = items.filter(item => item.type === 'folder').length;
    const expired = items.filter(item => item.is_expired).length;
    
    document.getElementById('totalItems').textContent = total;
    document.getElementById('scriptItems').textContent = scripts;
    document.getElementById('folderItems').textContent = folders;
    document.getElementById('expiredItems').textContent = expired;
}

// 渲染回收站项目
function renderRecycleItems() {
    const container = document.getElementById('recycleContainer');
    
    // 根据当前过滤器过滤项目
    let filteredItems = recycleItems;
    if (currentFilter !== 'all') {
        if (currentFilter === 'expired') {
            filteredItems = recycleItems.filter(item => item.is_expired);
        } else {
            filteredItems = recycleItems.filter(item => item.type === currentFilter);
        }
    }
    
    if (filteredItems.length === 0) {
        container.innerHTML = `
            <div class="text-center text-muted py-5">
                <i class="fas fa-trash-alt fa-3x mb-3"></i>
                <p>回收站为空</p>
            </div>
        `;
        return;
    }
    
    let html = '<div class="table-responsive"><table class="table table-hover">';
    html += `
        <thead>
            <tr>
                ${batchMode ? '<th width="40"><input type="checkbox" id="selectAllCheckbox" onchange="toggleSelectAll()"></th>' : ''}
                <th>类型</th>
                <th>名称</th>
                <th>原路径</th>
                <th>删除时间</th>
                <th>剩余天数</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
    `;
    
    filteredItems.forEach(item => {
        const isExpired = item.is_expired;
        const rowClass = isExpired ? 'table-danger' : '';
        const typeIcon = item.type === 'script' ? 'fas fa-file-code text-info' : 'fas fa-folder text-warning';
        const remainingDays = item.days_remaining;
        const remainingText = isExpired ? '已过期' : `${remainingDays}天`;
        const remainingClass = isExpired ? 'text-danger' : (remainingDays <= 7 ? 'text-warning' : 'text-success');
        
        html += `
            <tr class="${rowClass}" data-item-id="${item.id}">
                ${batchMode ? `<td><input type="checkbox" class="item-checkbox" value="${item.id}" onchange="updateSelection()"></td>` : ''}
                <td><i class="${typeIcon}"></i></td>
                <td>
                    <strong>${item.name}</strong>
                </td>
                <td><code>${item.path || '根目录'}</code></td>
                <td>${new Date(item.deleted_at).toLocaleString()}</td>
                <td><span class="${remainingClass}">${remainingText}</span></td>
                <td>
                    <div class="btn-group btn-group-sm">
                        <button type="button" class="btn btn-outline-success" onclick="restoreItem(${item.id})" title="恢复">
                            <i class="fas fa-undo"></i>
                        </button>
                        <button type="button" class="btn btn-outline-danger" onclick="permanentDeleteItem(${item.id})" title="永久删除">
                            <i class="fas fa-trash-alt"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `;
    });
    
    html += '</tbody></table></div>';
    container.innerHTML = html;
}

// 切换批量操作模式
function toggleBatchMode() {
    const toolbar = document.getElementById('batchToolbar');
    if (batchMode) {
        toolbar.style.display = 'block';
    } else {
        toolbar.style.display = 'none';
        clearSelection();
    }
    renderRecycleItems();
}

// 按类型过滤
function filterByType(type) {
    currentFilter = type;
    
    // 更新按钮状态
    document.querySelectorAll('[id^="filter"]').forEach(btn => {
        btn.classList.remove('active');
    });
    document.getElementById('filter' + type.charAt(0).toUpperCase() + type.slice(1)).classList.add('active');
    
    renderRecycleItems();
}

// 选择相关函数
function toggleSelectAll() {
    const selectAllCheckbox = document.getElementById('selectAllCheckbox');
    const itemCheckboxes = document.querySelectorAll('.item-checkbox');
    
    itemCheckboxes.forEach(checkbox => {
        checkbox.checked = selectAllCheckbox.checked;
    });
    
    updateSelection();
}

function selectAll() {
    const itemCheckboxes = document.querySelectorAll('.item-checkbox');
    itemCheckboxes.forEach(checkbox => {
        checkbox.checked = true;
    });
    updateSelection();
}

function clearSelection() {
    const itemCheckboxes = document.querySelectorAll('.item-checkbox');
    itemCheckboxes.forEach(checkbox => {
        checkbox.checked = false;
    });
    updateSelection();
}

function updateSelection() {
    const checkedBoxes = document.querySelectorAll('.item-checkbox:checked');
    selectedItems = Array.from(checkedBoxes).map(cb => parseInt(cb.value));
    
    document.getElementById('selectedCount').textContent = selectedItems.length;
    
    // 更新全选复选框状态
    const selectAllCheckbox = document.getElementById('selectAllCheckbox');
    const itemCheckboxes = document.querySelectorAll('.item-checkbox');
    if (selectAllCheckbox) {
        selectAllCheckbox.checked = itemCheckboxes.length > 0 && selectedItems.length === itemCheckboxes.length;
        selectAllCheckbox.indeterminate = selectedItems.length > 0 && selectedItems.length < itemCheckboxes.length;
    }
}

// 恢复项目
function restoreItem(itemId) {
    const item = recycleItems.find(i => i.id === itemId);
    if (!item) return;
    
    if (confirm(`确定要恢复 "${item.name}" 吗？`)) {
        fetch(`/api/recycle/restore/${itemId}`, {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast('恢复成功', 'success');
                loadRecycleItems();
            } else {
                showToast('恢复失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('恢复失败', 'error');
        });
    }
}

// 永久删除项目
function permanentDeleteItem(itemId) {
    const item = recycleItems.find(i => i.id === itemId);
    if (!item) return;
    
    if (confirm(`确定要永久删除 "${item.name}" 吗？此操作无法恢复！`)) {
        fetch(`/api/recycle/permanent-delete/${itemId}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast('永久删除成功', 'success');
                loadRecycleItems();
            } else {
                showToast('删除失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('删除失败', 'error');
        });
    }
}

// 批量恢复
function batchRestore() {
    if (selectedItems.length === 0) {
        showToast('请先选择要恢复的项目', 'warning');
        return;
    }
    
    const selectedItemsData = selectedItems.map(id => recycleItems.find(i => i.id === id));
    let itemsList = '<ul>';
    selectedItemsData.forEach(item => {
        itemsList += `<li>${item.name} (${item.type === 'script' ? '脚本' : '文件夹'})</li>`;
    });
    itemsList += '</ul>';
    
    document.getElementById('restoreItemsList').innerHTML = itemsList;
    new bootstrap.Modal(document.getElementById('restoreModal')).show();
}

// 确认批量恢复
function confirmRestore() {
    fetch('/api/recycle/batch-restore', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            item_ids: selectedItems
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast(`成功恢复 ${data.data.success_count} 个项目`, 'success');
            if (data.data.failed_count > 0) {
                // 显示失败项目的详细信息
                let failedMessage = `${data.data.failed_count} 个项目恢复失败`;
                if (data.data.failed_items && data.data.failed_items.length > 0) {
                    failedMessage += ':\n' + data.data.failed_items.join('\n');
                }
                showToast(failedMessage, 'warning');
            }
            loadRecycleItems();
            clearSelection();
        } else {
            showToast('批量恢复失败: ' + data.message, 'error');
        }
        bootstrap.Modal.getInstance(document.getElementById('restoreModal')).hide();
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('批量恢复失败', 'error');
        bootstrap.Modal.getInstance(document.getElementById('restoreModal')).hide();
    });
}

// 批量永久删除
function batchPermanentDelete() {
    if (selectedItems.length === 0) {
        showToast('请先选择要删除的项目', 'warning');
        return;
    }
    
    const selectedItemsData = selectedItems.map(id => recycleItems.find(i => i.id === id));
    let itemsList = '<ul>';
    selectedItemsData.forEach(item => {
        itemsList += `<li>${item.name} (${item.type === 'script' ? '脚本' : '文件夹'})</li>`;
    });
    itemsList += '</ul>';
    
    document.getElementById('deleteItemsList').innerHTML = itemsList;
    new bootstrap.Modal(document.getElementById('permanentDeleteModal')).show();
}

// 确认批量永久删除
function confirmPermanentDelete() {
    fetch('/api/recycle/batch-permanent-delete', {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            item_ids: selectedItems
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast(`成功删除 ${data.data.success_count} 个项目`, 'success');
            if (data.data.failed_count > 0) {
                // 构建详细的失败信息
                let failedMessage = `${data.data.failed_count} 个项目删除失败`;
                if (data.data.failed_items && data.data.failed_items.length > 0) {
                    failedMessage += '：' + data.data.failed_items.join(', ');
                }
                showToast(failedMessage, 'warning');
            }
            loadRecycleItems();
            clearSelection();
        } else {
            showToast('批量删除失败: ' + data.message, 'error');
        }
        bootstrap.Modal.getInstance(document.getElementById('permanentDeleteModal')).hide();
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('批量删除失败', 'error');
        bootstrap.Modal.getInstance(document.getElementById('permanentDeleteModal')).hide();
    });
}

// 清理过期项目
function cleanExpiredItems() {
    if (confirm('确定要清理所有过期项目吗？此操作无法恢复！')) {
        fetch('/api/recycle/clean-expired', {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast(`成功清理 ${data.data.cleaned_count} 个过期项目`, 'success');
                loadRecycleItems();
            } else {
                showToast('清理失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('清理失败', 'error');
        });
    }
}

// 刷新回收站项目
function refreshRecycleItems() {
    loadRecycleItems();
    showToast('刷新成功', 'success');
}

// 显示提示消息
function showToast(message, type = 'info') {
    // 这里使用现有的toast系统
    if (typeof window.showToast === 'function') {
        window.showToast(message, type);
    } else {
        alert(message);
    }
}
</script>
{% endblock %}